package com.n.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.n.application.SystemCache;
import com.n.common.BaseAction;
import com.n.dao.SupplierDao;
import com.n.model.Customer;
import com.n.model.Supplier;

@Controller
@RequestMapping("/supplier")
public class SupplierAction extends BaseAction {
	
	static final String PRE_PATH = "/admin/supplier/";
	
	@Autowired
	SupplierDao supplierDao;
	
	
	@RequestMapping(value="save.do")
	@ResponseBody
	public String save(HttpServletRequest request){
		String sid = request.getParameter("id");
		Supplier c = new Supplier();
		c.setName(request.getParameter("name"));
		c.setType(Integer.parseInt(request.getParameter("type")));
		c.setCode(request.getParameter("code"));;
		c.setLevel(Integer.parseInt(request.getParameter("level")));
		if(!StringUtils.isEmpty(sid)){
			c.setId(Integer.parseInt(sid));
		}
		supplierDao.merge(c);
		
		SystemCache.buildSupplier(supplierDao);
		
		return SUCCESS;
	}
	
	@RequestMapping(value="list.do")
	public String list(HttpServletRequest request, ModelMap model){
		List<Supplier> data = (List<Supplier>)supplierDao.loadAll(Supplier.class);
		model.put("data", processData(data));
		model.put("supplier_type_data", SystemCache.SUPPLIER_TYPE_LIST);
		return PRE_PATH + "index";
	}
	
	@RequestMapping(value="load.do")
	@ResponseBody
	public String load(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		Supplier c = supplierDao.load(Supplier.class, id);
		JSONObject json = JSONObject.fromObject(c);
		json.put("success", SUCCESS);
		System.out.println(json);
		return json.toString();
	}
	
	@RequestMapping(value="del.do")
	@ResponseBody
	public String del(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		supplierDao.del(id);
		
		SystemCache.buildSupplier(supplierDao);
		
		return SUCCESS;
	}
	
	private List<Supplier> processData(List<Supplier> data){
		for (Supplier c : data) {
			c.setTypeName(SystemCache.SUPPLIER_TYPE_MAP.get(c.getType()));
		}
		return data;
	}

}
